package com.example.cstr.controller;

import com.example.cstr.config.FileConfig;
import com.example.cstr.entity.Message;
import com.example.cstr.service.FileService;
import com.example.cstr.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api/file")
@Api(tags = "全局文件上传模块")
public class FileController {

    @Resource
    private FileConfig config;

    @Resource
    private FileService fileService;

    @PostMapping("/addFile")
    @ApiOperation(value = "文件上传，返回文件名数组")
    public Message fileUpload(MultipartFile[] files) throws IOException {
        if (files.length>0) {

            String rs= FileUtils.saveFileToTempDir(config.FilePath,config.hostUrl,files);

            return Message.success(null).add(rs);
        }
        return Message.fail("没有读取到您的上传文件信息");
    }

    @PostMapping("/removeFile")
    @ApiOperation(value = "文件删除")
    public Message removeFile(String fileName) throws IOException {
//            System.out.println(config.FilePath);
            //根据文件的路径获取此文件
            File file = new File(config.FilePath + "/" + fileName);
            //判断此文件是否为空
            if(file!=null){
                //文件不为空，执行删除
                file.delete();
            }else {
                //为空提示错误信息
                return Message.fail("文件不存在，不能删除");
            }
        //数据库中删除文件数据
        return fileService.removeMyFileByOrdName(fileName)>0?Message.success("文件和数据库删除成功"):Message.success("文件删除成功");
    }
}
